# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 17:31:17 2017

@author: zsuir
"""

from PyQt5 import QtWidgets,QtCore,QtGui
import sys
import json
import re
import readmdict
import subprocess
import os
with open('qss.css','r') as fp:
	qss=fp.read()
with open('history.cfg','r') as fp:
	h=json.loads(fp.read())
app = QtWidgets.QApplication(sys.argv)
app.setApplicationName('Dict')
app.setStyleSheet(qss)
dialog=QtWidgets.QDialog()
gridLayout = QtWidgets.QGridLayout(dialog)
vlayout=QtWidgets.QVBoxLayout()
vlayout2=QtWidgets.QVBoxLayout()
txinput=QtWidgets.QLineEdit()	#搜索输入框
words=QtWidgets.QListWidget()	#单次选择框
la=QtWidgets.QTextBrowser()	#词典显示框
history=QtWidgets.QListWidget() #搜索历史
note=QtWidgets.QLineEdit()	#历史项提示
tmp=list(h.keys())
tmp.remove('fdict')
history.addItems([t+'\t'+h[t] for t in tmp])
try:
	if(os.path.isfile(h['fdict'])):
		d=readmdict.MDX(h['fdict'])
	else:
		raise
except:
	filename = QtWidgets.QFileDialog.getOpenFileName(dialog,'Open File', '', \
                                                       'Dict (*.mdx *.mdd)')
	h['fdict'] =filename[0]
	print(h['fdict'])
	d=readmdict.MDX(h['fdict'])


txinput.setMinimumSize(QtCore.QSize(200, 30))
words.setMinimumSize(QtCore.QSize(100, 30))
la.setMinimumSize(QtCore.QSize(500, 600))
txinput.setText('- -')

#gridLayout.addWidget(txinput, 0, 0, 1, 1)
gridLayout.addWidget(words, 0, 2, 1, 1)
gridLayout.addLayout(vlayout, 0, 0, 1, 1)
gridLayout.addLayout(vlayout2, 0, 1, 1, 1)
vlayout.addWidget(history,0)
vlayout.addWidget(note,1)
vlayout2.addWidget(txinput,0)
vlayout2.addWidget(la,1)

font=app.font()
font.setPointSize(16)
app.setFont(font)
global itm
itm=[]
def returnPressed():
	global h
	wd=str(txinput.text()).strip()
	if(str(note.text()) != ''):
		h[wd]=str(note.text())
		history.clear()
		tmp=list(h.keys())
		tmp.remove('fdict')
		history.addItems([t+'\t'+h[t] for t in tmp])
	search(wd)
	
def search(wd):
	global itm
	words.clear()
	wd=wd.replace('-','\w*')+'$'
	pattern = re.compile(wd)
	itm={k.decode():v for k,v in d.items() if pattern.match(k.decode())}
	key=list(itm.keys())
	key.sort()
	words.addItems(key)
			
def wordchange(key):
	global itm
	key=str(words.currentItem().text()).strip()#words.currentText()
	if key == '':
		la.clear()
		return
	la.setText(itm[key].decode('utf8'))
	
def readhistory():
	wd=str(history.currentItem().text()).strip()
	wd=wd.split('\t')[0]
	txinput.setText(wd)
	note.setText(h[wd])
	search(wd)
	
def delhistory(event):
	if event.key() == QtCore.Qt.Key_Delete:
		global h
		h.pop(str(history.currentItem().text().split('\t')[0]))
		history.clear()
		tmp=list(h.keys())
		tmp.remove('fdict')
		history.addItems([t+'\t'+h[t] for t in tmp])
		txinput.clear()
		words.clear()
		note.clear()
		la.clear()
	
def closefunc(dialog):
	global h
	#print(h)
	subprocess.run('rm history.cfg')
	with open('history.cfg','w') as fp:
		json.dump(h,fp)
	
txinput.returnPressed.connect(returnPressed)
txinput.textChanged.connect(note.clear)
words.itemClicked.connect(wordchange)
history.itemClicked.connect(readhistory)
note.returnPressed.connect(returnPressed)
history.keyPressEvent=delhistory
dialog.closeEvent=closefunc
dialog.show()
app.exec_()
app.quit()
